package com.zhi.inisyccalllog.util;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.text.TextUtils;

import androidx.core.app.ActivityCompat;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.List;

public class ASNetworkUtil {

    public static final String KEY_BSSID = "bssid";
    public static final String KEY_SSID = "ssid";
    public static final String KEY_MAC = "mac";
    public static final String KEY_NAME = "name";
    public static final String KEY_LEVEL = "level";
    public static final String KEY_FREQUENCY = "frequency";

    public static String getMacAddress(Context context) {
        String macAddress = "";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            try {
                Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
                while (enumeration.hasMoreElements()) {
                    StringBuilder stringBuilder = new StringBuilder();
                    NetworkInterface networkInterface;
                    byte[] arrayOfByte;
                    if ((arrayOfByte = (networkInterface = enumeration.nextElement()).getHardwareAddress()) == null || arrayOfByte.length == 0)
                        continue;
                    int i = arrayOfByte.length;
                    for (byte b = 0; b < i; b++) {
                        byte b1 = arrayOfByte[b];
                        stringBuilder.append(String.format("%02X:", new Object[]{Byte.valueOf(b1)}));
                    }
                    if (stringBuilder.length() > 0)
                        stringBuilder.deleteCharAt(stringBuilder.length() - 1);
                    String str1 = stringBuilder.toString();
                    //ASLogger.d("mac", "interfaceName=" + networkInterface.getName() + ", mac=" + str1);
                    if (networkInterface.getName().equals("wlan0")) {
                        //ASLogger.d("mac", " interfaceName =" + networkInterface.getName() + ", mac=" + str1);
                    } else {
                        str1 = macAddress;
                    }
                    macAddress = str1;
                }
                enumeration = null;
            } catch (SocketException socketException) {
                socketException.printStackTrace();
            }
        } else {
            try {
                @SuppressLint("WifiManagerPotentialLeak")
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                WifiInfo info = wifiManager.getConnectionInfo();
                @SuppressLint("HardwareIds")
                String gmac = info.getMacAddress();
                macAddress = gmac;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (TextUtils.isEmpty(macAddress)) {
            macAddress = "";
        }
        return macAddress;
    }

    public static String getIPAddress(Context paramContext) {
        try {
            NetworkInfo info = ((ConnectivityManager) paramContext.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                if (info.getType() == ConnectivityManager.TYPE_MOBILE||info.getType() == ConnectivityManager.TYPE_ETHERNET) {
                    //当前使用2G/3G/4G网络
                    try {
                        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                            NetworkInterface anInterface = en.nextElement();
                            for (Enumeration<InetAddress> enumIpAddr = anInterface.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                                InetAddress inetAddress = enumIpAddr.nextElement();
                                if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                                    return inetAddress.getHostAddress();
                                }
                            }
                        }
                    } catch (SocketException e) {
                        e.printStackTrace();
                    }

                } else if (info.getType() == ConnectivityManager.TYPE_WIFI) {
                    //当前使用无线网络
                    @SuppressLint("WifiManagerPotentialLeak")
                    WifiManager wifiManager = (WifiManager) paramContext.getSystemService(Context.WIFI_SERVICE);
                    if (wifiManager == null) {
                        return "";
                    }
                    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                    if (wifiInfo == null) {
                        return "";
                    }
                    return converToIPString(wifiInfo.getIpAddress());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String converToIPString(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }

    public static String getCurrentWifi(Context context) {
        String curWifi = "";
        try {
            JSONObject jsonObject = new JSONObject();
            @SuppressLint("WifiManagerPotentialLeak")
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            if (wifiInfo != null) {
                String bssid = ASUtil.safeString(wifiInfo.getBSSID());
                String ssid = ASUtil.safeString((wifiInfo.getSSID().replace("\"", "")));
                String mac = ASUtil.safeString(getMacAddress(context));
                if (TextUtils.isEmpty(bssid)) {
                    ssid = "";
                }
                jsonObject.put(KEY_BSSID, bssid);
                jsonObject.put(KEY_SSID, ssid);
                jsonObject.put(KEY_MAC, mac);
            }
            curWifi = jsonObject.toString();
            //ASLogger.d("getCurrentWifi", curWifi);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return curWifi;
    }

    public static String getConfiguredWifi(Context context) {
        String configWifi = "";
        try {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
                    ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                JSONArray jsonArray = new JSONArray();
                @SuppressLint("WifiManagerPotentialLeak")
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                List<ScanResult> scanResults = wifiManager.getScanResults();
                for (int i = 0; i < scanResults.size(); i++) {
                    ScanResult scanResult = scanResults.get(i);
                    String bssid = ASUtil.safeString(scanResult.BSSID);
                    String ssid = ASUtil.safeString((scanResult.SSID.replace("\"", "")));
                    String mac = "";
                    String level = ASUtil.safeString(String.valueOf(scanResult.level));
                    String frequency = ASUtil.safeString(String.valueOf(scanResult.frequency));
                    if (!TextUtils.isEmpty(bssid)) {
                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put(KEY_BSSID, bssid);
                        jsonObject.put(KEY_SSID, ssid);
                        jsonObject.put(KEY_NAME, ssid);
                        jsonObject.put(KEY_MAC, mac);
                        jsonObject.put(KEY_LEVEL, level);
                        jsonObject.put(KEY_FREQUENCY, frequency);
                        jsonArray.put(jsonObject);
                    }
                }
                configWifi = jsonArray.toString();
                scanResults.clear();
                scanResults = null;
                jsonArray = null;
                //ASLogger.d("getConfiguredWifi", configWifi);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return configWifi;
    }

    public static String getWifiCount(Context context) {
        String wifiCount = "";
        try {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
                    ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                @SuppressLint("WifiManagerPotentialLeak")
                WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
                List<ScanResult> scanResults = wifiManager.getScanResults();
                int count = 0;
                for (int i = 0; i < scanResults.size(); i++) {
                    ScanResult scanResult = scanResults.get(i);
                    String bssid = ASUtil.safeString(scanResult.BSSID);
                    if (!TextUtils.isEmpty(bssid)) {
                        count += 1;
                    }
                }
                wifiCount = count + "";
                scanResults.clear();
                scanResults = null;
                //ASLogger.d("getWifiCount", wifiCount);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return wifiCount;
    }

    public static String getVpnState(Context paramContext) {
        String state = "NO";
        try {
            ConnectivityManager cm = (ConnectivityManager) paramContext.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (cm == null) {
                return "NO";
            }

            NetworkInfo networkInfo = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_VPN);
            }
            if (networkInfo == null) {
                return "NO";
            }
            if (networkInfo.isConnectedOrConnecting()) {
                state = "YES";
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return state;
    }

    public static String getIsWifiProxy(Context context) {
        // 是否大于等于4.0
        String isProxy = "NO";
        try {
            String proxyAddress;
            int proxyPort;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                proxyAddress = System.getProperty("http.proxyHost");
                String portStr = System.getProperty("http.proxyPort");
                proxyPort = Integer.parseInt((portStr != null ? portStr : "-1"));
            } else {
                proxyAddress = android.net.Proxy.getHost(context);
                proxyPort = android.net.Proxy.getPort(context);
            }

            if ((!TextUtils.isEmpty(proxyAddress)) && (proxyPort != -1)) {
                isProxy = "YES";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return isProxy;
    }
}
